import axios from "axios";
import { BACKEND_URL, getUrl, goTo, setIdContent } from "./tool";


class Basic{
    constructor(){
        this.csrf_token = null;

        //创建Axios对象
        this.axios = axios.create({
            baseURL: BACKEND_URL,
            withCredentials: true,  // 允许携带Cookie
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
            }
        })

        //记录最后一次请求的时间戳
        this.lastRequestTime = 0;
    }

    //获取csrfToken
    async get_token(){
        await this.axios({
            method: 'get',
            url: 'api/csrf/'
        })
        .then((request) => {
            this.csrf_token = request.data['csrfToken'];
        })
    }

    //防抖
    canSend(time, is_alert=true){
        const now = Date.now();     //获取此刻时间戳

        //第一次操作,直接放行
        if (this.lastRequestTime === 0){
            this.lastRequestTime = now;
            return true;
        }

        if (now - this.lastRequestTime < time * 1000){
            if (is_alert){
                alert(`操作太频繁, 请${time}秒后再试`)
            }
            return false;
        }

        //更新时间戳
        this.lastRequestTime = now;
    
        return true;
    }

    //检查登录状态
    async check_session(){
        await this.axios({
            method: 'get',
            url: 'api/check_session/',
        })
        .then((request) => {
            const isLoggedIn = request.data['isLoggedIn'];  // 登录状态
            const this_url = window.location.href;      // 获取当前的URL
            
            if (isLoggedIn && this_url === getUrl('check_in')){
                goTo('me', "哈哈哈, 你居然不知道自己已经登录好了")
            }else if (isLoggedIn && this_url === getUrl('')){
                goTo('me', "欢迎回来, 口袋居民")
            }else if (isLoggedIn === false){
                if (this_url !== getUrl('') && this_url !== getUrl('check_in')){
                    goTo('', "你还没登录! ")
                }
            }
        })
    }
}

export class Api extends Basic{
    constructor(){
        super();
    }

    //用户注册
    async check_in(data){   
        await this.get_token(); // 先获取CSRFToken   
        if (!this.canSend(10)) { return; } // 防抖处理
        this.axios({
            method: 'post',
            url: 'api/check_in/',
            headers: {
                'X-CSRFToken': this.csrf_token
            },
            data: data
        })
        .then(response => {
            const message = response.data['message'];
            if (message === '登录成功') {
                goTo('me', '欢迎回来!');
            } else if (message === '注册成功') {
                goTo('me', '成功见证了一个口袋居民的诞生!');
            } else{
                alert(message);
            }
        })
        .catch(error => {
            console.error("请求出错：", error);
        });
    }

    //获取用户信息
    async get_user(){
        await this.axios({
            method: 'get',
            url: 'api/get_user/'
        })
        .then((request) => {
            const message = request.data['message'];
            if (message === 'success'){
                const user_data = request.data['user_data'];
                setIdContent('username', user_data['username']);
                setIdContent('gold-num', user_data['gold']);
            }
        })
    }

    //获取签到信息
    async get_check_data(){
        await this.axios({
            method: 'get',
            url: 'api/get_check_data/'
        })
        .then((request) => {
            const data = request.data['check_data'];
            
            const day_in_week = data['day'] % 7;    //通过取余来获取本周签到天数

            //设置样式
            for (let i = 0; i < day_in_week; i++){
                const item = document.getElementById(`day-${i+1}`);     //获取day小卡片
                item.style.backgroundColor = "rgb(5, 205, 255)";
                item.style.color = "black";
            }

            //设置签到天数
            setIdContent("checkin-num", `已签到: ${data['day']} 天`)
        })
    }

    //签到操作
    async check_one_day(){
        if (!this.canSend(10)) { return; } // 防抖处理
        await this.axios({
            method: 'get',
            url: 'api/check_one_day/',
        })
        .then((request) => {
            //设置样式
            const data = request.data['check_data'];
            const day_in_week = data['day'] % 7;    //通过取余来获取本周签到天数

            if (data === 'error'){      
                alert("今天已签到!")
                return 0;   //哈哈,为了致敬C语言
            }

            for (let i = 0; i < day_in_week; i++){
                const item = document.getElementById(`day-${i+1}`);     //获取day小卡片
                item.style.backgroundColor = "rgb(5, 205, 255)";
                item.style.color = "black";
            }

            setIdContent("checkin-num", `已签到: ${data['day']} 天`)
            setIdContent("gold-num", Number(request.data['gold']).toFixed(2));
            alert("签到成功!")
        })
    }

    //获取我的所有订单
    async get_orders(){
        const response = await this.axios({
            method: 'get', 
            url: 'api/get_orders/',
        })
        return response.data;
    }

    //获取随机商品外观
    async get_random_appearance(){
        if (!this.canSend(2, false)) { return; } // 防抖处理
        
        const response = await this.axios({
            method: 'get',
            url: 'api/get_random_appearance/'
        })
        return response.data;
    }

    //添加商品
    async add_product(name, price, description, colors){
        await this.get_token(); // 先获取CSRFToken
        await this.axios({
            method: 'post',
            url: 'api/add_product/',
            headers: {
                'X-CSRFToken': this.csrf_token
            },
            data: {
                'name': name, 
                'price': price,
                'description': description,
                'colors': colors
            }
        }).then((request) => {
            if (request.data['message'] === 'success'){
                goTo('capsule', '商品制造成功!')
            }else if (request.data['message'] === 'zero'){
                alert("价格不能为0!")
            }else if (request.data['message'] === 'repeat'){
                alert("已有该商品!")
            }else if (request.data['message'] === 'description_none'){
                alert("描述为空!")
            }
        }).catch(error => {
            console.clear()
            alert("你输入的信息不合规哦!")
        })
    }

    //获取我制造的所有商品
    async get_product(){
        const response = await this.axios({
            method: 'get',
            url: 'api/get_product/'
        })
        return response.data['data'];
    }

    //获取集市中的物品
    async get_market_data(page){
        const response = await this.axios({
            method: 'get',
            url: `api/get_market_data?page=${page}`
        })
        return response.data['data'];
    }

    //购买商品
    async buy(product_id){
        await this.get_token(); // 先获取CSRFToken
        await this.axios({
            method: 'post',
            url: 'api/buy/',
            headers: {
                'X-CSRFToken': this.csrf_token
            },
            data: {
                'product_id': product_id
            }
        }).then(response => {
            // 执行跳转
            if (response.data['message'] === 'error'){
                alert("你的口袋币不够!")
            }else{
                goTo('order', response.data['message'])
            }
        })
    }

    async delete(product_id){
        await this.get_token();
        await this.axios({
            method: 'post',
            url: 'api/delete/',
            headers: {
                'X-CSRFToken': this.csrf_token
            },
            data: {
                'product_id': product_id
            }
        }).then(response => {
            goTo('capsule', response.data['message'])
        })
    }
}